package com.gh.service.impl;

import com.aliyun.oss.OSSClient;
import com.gh.service.FileService;
import com.gh.util.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author Eric
 * @Date 2021/6/20 20:24
 * @Version 1.0
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile file) {

        try {
            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(ConstantPropertiesUtils.ENDPOINT, ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.SECRET);
            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            //  InputStream inputStream = new FileInputStream("D:\\localpath\\examplefile.txt");
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            InputStream in = file.getInputStream();
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + filename;
            String date = new DateTime().toString("yyyy/MM/dd");
            filename = date + "/" + filename;
            ossClient.putObject(ConstantPropertiesUtils.BUCKETNAME, filename, in);
            // 关闭OSSClient。
            ossClient.shutdown();
            //https://eric123.oss-cn-shanghai.aliyuncs.com/0406_1.jpg
            String path = "http://" + ConstantPropertiesUtils.BUCKETNAME + "." + ConstantPropertiesUtils.ENDPOINT + "/" + filename;
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
